package uk.gov.swmprobation.cpvisibility;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedIconOverlay.OnItemGestureListener;
import org.osmdroid.views.overlay.ItemizedOverlayWithFocus;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.OverlayItem;

import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Path.Direction;
import android.graphics.Point;
import android.graphics.Region.Op;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;

public class SearchProjects extends MyActivity {

	private double lat;
	private double lng;
	private MyOpenViewMap myOpenMapView;
	private MapController myMapController;
	private GeoPoint point;
	private Point circleCenter;
	private float radiusmeters=0;
	private ItemizedOverlayWithFocus<OverlayItem> mMyLocationOverlay;
	private CircleOverlay highlightCircle;
	
	private ArrayList<OverlayItem> markerItems;
	
	Drawable markerRedImage,markerYellowImage,markerBlueImage,markerGreenImage;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		//Show Hint each time until setting changed
		if (sharedPref.getBoolean(SettingsActivity.searchHintTitle, true)){
			Helper.showHintDialog(this, SettingsActivity.searchHintTitle, SettingsActivity.searchHintMessage);
		}
		setContentView(R.layout.activity_search_projects);
		initVariables();
        
        myMapController.setCenter(point);
        myOpenMapView.allowZoom=true;
        setProjectMarkers();
        ViewTreeObserver vto = myOpenMapView.getViewTreeObserver(); 
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
            @Override 
            public void onGlobalLayout() { 
            	SearchProjects.this.myOpenMapView.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
            	searchPoint();
            } 
        });
        
        //myOpenMapView.getOverlays().add(highlightCircle);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.application_menu, menu);
		return true;
	}
	
	private void initVariables(){
		Bundle extras = getIntent().getExtras();
		lat = extras.getDouble("lat",0.0);
		lng = extras.getDouble("lng",0.0);
		myOpenMapView = (MyOpenViewMap)findViewById(R.id.openmapview);
        myMapController = myOpenMapView.getController();
        myOpenMapView.setBuiltInZoomControls(false);
        myOpenMapView.setMultiTouchControls(true);
        myMapController.setZoom(16);
        point = new GeoPoint(lat, lng);
        highlightCircle = new CircleOverlay(this);
	}
	
	private void searchPoint(){
		markerItems = new ArrayList<OverlayItem>();
		myOpenMapView.getOverlays().remove(mMyLocationOverlay);
		new getMarkerItems().execute();
		myMapController.setCenter(point);
		lat=point.getLatitudeE6()/1000000.0;
		lng=point.getLongitudeE6()/1000000.0;
		myOpenMapView.getOverlays().remove(highlightCircle);
		highlightCircle = new CircleOverlay(this);
		myOpenMapView.getOverlays().add(highlightCircle);
	}
	
	private Drawable getMarker(int markerDrawable){
		Drawable markerImage=getResources().getDrawable(markerDrawable);
        markerImage.setBounds(0, 0, markerImage.getIntrinsicWidth(),markerImage.getIntrinsicHeight());
        return markerImage;
	}
	private void setProjectMarkers(){
		markerRedImage=getMarker(R.drawable.markerred);
		markerYellowImage=getMarker(R.drawable.markeryellow);
        markerBlueImage=getMarker(R.drawable.markerblue);
		markerGreenImage=getMarker(R.drawable.markergreen);
	}
	
	public static float metersToRadius(final MapView map, final float meters, final double latitude) {
        return (float) (map.getProjection().metersToEquatorPixels(meters) * (1 / Math.cos(Math.toRadians(latitude))));
    }
	
	public class getMarkerItems extends
    AsyncTask<Void, Integer, String> {

		@Override
		  protected void onPreExecute() {
			findViewById(R.id.loadingmessage).setVisibility(View.VISIBLE);
		  }
		
		@Override
		protected String doInBackground(Void... params) {
			StringBuilder builder = new StringBuilder();
		    HttpClient client = new DefaultHttpClient();
		    String searchUrl ="http://env-2768543.jelastic.dogado.eu/solr/core0/select?q=*%3A*&fq=id:[540%20TO%20*]&sort=geodist()asc&fl=id%2Clocation%2Cstatus%2Cgeodist()&wt=json&spatial=true&pt="+lat+"%2C"+lng+"&sfield=location&rows=20";
		    HttpGet httpGet = new HttpGet(searchUrl);
		    try {
		      HttpResponse response = client.execute(httpGet);
		      StatusLine statusLine = response.getStatusLine();
		      int statusCode = statusLine.getStatusCode();
		      if (statusCode == 200) {
		        HttpEntity entity = response.getEntity();
		        InputStream content = entity.getContent();
		        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
		        String line;
		        while ((line = reader.readLine()) != null) {
		          builder.append(line);
		        }
		      } else {
		        Log.e(SearchProjects.class.toString(), "Failed to download file");
		      }
		    } catch (ClientProtocolException e) {
		      e.printStackTrace();
		    } catch (IOException e) {
		      e.printStackTrace();
		    }
		    return builder.toString();
		}
		
		@Override
		  protected void onPostExecute(String jString) {;
			JSONObject jObject;
			GeoPoint markerpoint;

			try {
				jObject = new JSONObject(jString);
				JSONArray projectsArray = jObject.getJSONObject("response").getJSONArray("docs");
				OverlayItem markerItem;
				if(projectsArray.length()==0){
					findViewById(R.id.loadingmessage).setVisibility(View.GONE);
					return;
					}
				int n=projectsArray.length();
				for (int i = 0; i < n; i++){
					radiusmeters = (float) projectsArray.getJSONObject(i).getDouble("geodist()");
					int id = projectsArray.getJSONObject(i).getInt("id");
					String status = projectsArray.getJSONObject(i).getString("status");
					String location = projectsArray.getJSONObject(i).getString("location");
					String[] splitLocation = location.split(",");
					double lat = Double.parseDouble(splitLocation[0]);
					double lng = Double.parseDouble(splitLocation[1]);
					markerpoint = new GeoPoint(lat, lng);
					markerItem = new OverlayItem(String.valueOf(id), "Status "+status, markerpoint);
					if(status.equals("complete")){
						markerItem.setMarker(markerBlueImage);
					} else if(status.equals("new")){
						markerItem.setMarker(markerGreenImage);
					} else if(status.equals("inprogress")){
						markerItem.setMarker(markerYellowImage);
					} else {
						markerItem.setMarker(markerRedImage);
					}

			        markerItems.add(markerItem);			        
				}
				mMyLocationOverlay = new ItemizedOverlayWithFocus<OverlayItem>(SearchProjects.this, markerItems, new OnItemGestureListener<OverlayItem>() {
                    @Override
                    public boolean onItemSingleTapUp(final int index, final OverlayItem item) {
                    	Intent openProjectView = new Intent(SearchProjects.this, ProjectReview.class);
                        int projectIdToOpen = Integer.parseInt(item.mTitle);
                        openProjectView.putExtra("project_id", projectIdToOpen);
                        openProjectView.putExtra("updated", true);
                        startActivity(openProjectView);
                        return true;
                    }

                    @Override
                    public boolean onItemLongPress(final int index, final OverlayItem item) {
                        return false;
                    }
                });
				mMyLocationOverlay.setFocusItemsOnTap(false);
      		    myOpenMapView.getOverlays().add(mMyLocationOverlay);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			findViewById(R.id.loadingmessage).setVisibility(View.GONE);
		  }
		
	}
	
	public void searchHere(View view) {
		Log.e("SP","search here");
		point = (GeoPoint) myOpenMapView.getMapCenter();
		searchPoint();
	}

    private class CircleOverlay extends Overlay {
        public CircleOverlay(final Context context) {
            super(context);
        }

        public void draw(final Canvas canvas, final MapView mv, final boolean shadow) {
            if(shadow)
                return;
            
            final float radiuspixels = metersToRadius(mv, radiusmeters, lat)*1000;
            final Path path=new Path();
            final Paint paint  = new Paint();
            paint.setStrokeWidth(0);
            paint.setARGB(100, 200, 0, 0);
            paint.setStyle(Paint.Style.STROKE);
            circleCenter = mv.getProjection().toPixels(point,null);
            path.addCircle(circleCenter.x, circleCenter.y, radiuspixels, Direction.CW);

            canvas.drawPath(path, paint);
            canvas.clipPath(path, Op.DIFFERENCE);
            canvas.drawARGB(100, 100, 100, 100);
            canvas.clipPath(path, Op.UNION);
        }
    }
}